#!/usr/bin/env python
# encoding: utf-8
from douban.client import OAuthClient
from douban.service import DoubanService

from appscript import app,k

import urllib

import time

import string

class Douban_Client:
	apikey   =""
	apisecret=""
	
	accesskey   =""
	accesssecret=""
	uid         =""
	
	service = {}
	
	last_time = 0
	request_count = 0
	
	def __init__(self,key,secret):
		self.apikey = key
		self.apisecret = secret
		
	
	def requestLimit(self,num=1):
		LIMIT = 40
		now = time.time()
		gap = now - self.last_time
		if gap > 60 :
			self.last_time = now
			self.request_count = 0
		elif self.request_count > LIMIT :
			#print "Wait for ",gap," seconds."
			time.sleep( gap )
		self.request_count = self.request_count + num
		pass
		
		
	#use Safari to open a URL
	def openURL(self,url):
		safari = app(u"Safari")
		safari.make(new=k.document,with_properties={k.URL:url})


	def setAccess(self,key,secret):
		self.accesskey = key
		self.accesssecret = secret
		return self
		

	def access(self):
		server = "http://www.douban.com"
		client = OAuthClient(key=self.apikey,secret=self.apisecret)
		try:
			#get request key and secret
			request,request_secret = client.get_request_token()
		except Exception:
			print "Please check your internet connect."
			
		if request and request_secret:
			#print "success get request token"
			
			url = client.get_authorization_url(request,request_secret)
			self.openURL(url)
			self.oauthclient = client
			return request,request_secret
	
	def access_ok(self,request,request_secret):
			#print "\nyes,now get access token."
			self.accesskey,self.accesssecret,self.uid = self.oauthclient.get_access_token(request,request_secret)
			return
	
	
	def login(self):
		self.service = DoubanService(api_key=self.apikey,secret=self.apisecret)
		if self.accesskey and self.accesssecret:
			re = self.service.ProgrammaticLogin(self.accesskey,self.accesssecret)
			#print "Login success"
			return re
		else:
			return False
	
	def search(self,album,artist=False):
		CODE = 'utf-8'
		
		if artist:
			q=album+" "+artist
		else:
			q=album
		
		q = q.encode(CODE)
		#print q.decode(CODE)
		#q = self.urlencode(q)
		#print q
		
		self.requestLimit(1)
		
		try:
			feed = self.service.SearchMusic(q)
		except Exception:
			return False
		#feed = feed.decode('utf-8')
		
		for music in feed.entry:
			title = music.title.text.decode(CODE)
			
			#print title
			
			#url   = music.id.text.decode(CODE)
			
			#print url
			#print artist
			if artist:
				for people in music.author:
					name = people.name.text.decode(CODE)
					if name in artist or artist in name:
						return music
			else:
				if title == album:
					return music

		#No found
		return False
	
	def urlencode(self,s):
		#p = repr(s).replace(r'\x','%')
		#return p[1:-1]
		return urllib.quote(s.encode('utf8'))
		#d = {'':s}
		#str = urllib.urlencode(d)
		#return str[1:]
		
		
	def getCollection(self,url):
		
		self.requestLimit(1)
		try:
			feed = self.service.GetMusic(url)
		except Exception:
			return False
		
		for li in feed.link:
			if li.rel == 'collection':
				return li.href
		return False
	
	def getRating(self,url):
		self.requestLimit(1)
		try:
			feed = self.service.GetCollection(url)
		except Exception:
			return False

		if(feed.rating):
			return feed.rating.value
		else:
			return False
		
	def addCollection(self,subject,status="listened",rating=None):
		#print "Now add subject - " + subject.id.text
		self.requestLimit(1)
		try:
			self.service.AddCollection(status, subject, rating , [] , False)
		except Exception:
			return False
	
class iTunes_Client:
	
	i = []
	
	#The list of tracks
	tracks = []
	
	#The length of tracks list
	length = 0
	
	#The counter of tracks
	n = 0
	
	
	
	def __init__(self):
		self.i = app("iTunes")
		self.i.run()
	
	#selections in browser window
	def select(self):
		self.tracks = self.i.browser_windows()[0].selection()
		self.initTracks()
		return self
		
	#all in browser window
	def all(self):
		self.tracks = self.i.browser_windows()[0].view().tracks()
		self.initTracks()
		return self
	
	def initTracks(self):
		if self.tracks:
			self.length = len(self.tracks)
			self.n      = 0
		
	def next(self):
		if self.n < self.length:
			self.n = self.n+1
			return self.tracks[self.n-1]
		else:
			return False


def main():
	#This is douban api key & api key secret
	client = Douban_Client("078112bd73a836d4168338385af8a47c","8a4a9cb90cd55ac5")
	#client.access()
	client.setAccess("d2a19c5dcafe6d3d77e4d51960fb47b7","ff8a8ca4b8a411fe").login()
	people = client.service.GetAuthorizedUID('/people/@me')
	print "This is "+people.uid.text
	
	client.search("We Sing, We Dance, We Steal Things" ,"Colbie Caillat/Jason Mraz")
	
	exit('test exit')
	#test search
	#q = u"我爱南京"
	#print client.search(q)
	#exit()
	#
	tunes = iTunes()
	tunes.select()
	track = tunes.next()
	
	#print track
	
	while(track):
		#print track.artist() , track.album() , track.album_rating()/20
		
		subject = client.search( track.album() , track.artist() )
		
		if subject :
			collection = client.getCollection(subject.id.text)
			# You have collect this album
			if collection :
				i_rating = track.album_rating()/20
				d_rating = string.atoi( client.getRating(collection) )
				
				if i_rating  == d_rating:
					break
				else:
					print "Now sync Collection="  +  collection + "From" , d_rating , "to" , i_rating
					#Use iTunes Rating
					feed = client.service.GetCollection(collection)
					client.service.UpdateCollection(feed,'listened',[],i_rating)
					
			else:
				#rating == 0 -> listening ; rating > 0 -> has listened
				#print "New Album"+track.album()
				
				client.addCollection(subject)
				
		else:
			print "Can't find album "+track.album()

		track = tunes.next()
	
	#client.addCollection("http://api.douban.com/music/subject/4924002")	
	
if __name__ == '__main__':
	main2()